<template>
  <view class="page bg-white">
    <CommonNavbar :title="state.questionInfo.title"></CommonNavbar>
    <view class="main padding-lr">
      <up-text color="#333" :text="state.questionInfo.description"></up-text>

      <up-form labelPosition="top" labelWidth="auto" :model="form" :rules="rules" ref="uForm">
        <up-form-item :prop="`form.answer.${index}.option_ids`" :label="`${index + 1}. ${item.question_text}`"
          v-for="(item, index) in state.questionInfo.questions" :key="item.id">
          <!-- 多选 -->
          <template v-if="item.question_type === 'multiple'">
            <checkbox-group @change="form.answer[index].option_ids = $event.detail.value">
              <label class="uni-list-cell uni-list-cell-pd" v-for="(option, index) in item.options" :key="option.id">
                <view>
                  <checkbox :value="option.option_num" color="#7da02f" style="transform: scale(0.7)" />{{ option.text }}
                </view>
              </label>
            </checkbox-group>
          </template>
          <!-- 单选 -->
          <template v-if="item.question_type === 'single'">
            <radio-group @change="form.answer[index].option_ids[0] = $event.detail.value">
              <label class="uni-list-cell uni-list-cell-pd" v-for="option in item.options" :key="option.option_num">
                <view>
                  <radio color="#7da02f" :value="option.option_num" style="transform: scale(0.7)" />{{ option.text }}
                </view>
              </label>
            </radio-group>
          </template>
          <!-- 打分 -->
          <template v-if="item.question_type == 'scale'">
            <view class="flex margin-top-xs">
              <up-text size="14" color="#666" text="很不符合"></up-text>
              <up-text size="14" color="#666" align="right" text="很符合"></up-text>
            </view>
            <view class="custom-rate">
              <view class="item" v-for="option in item.options" :key="option.option_num"
                @click="form.answer[index].option_ids[0] = option.option_num"
                :class="{ active: option.option_num <= form.answer[index].option_ids[0] }">
                {{ option.text }}
              </view>
            </view>
          </template>
          <!-- 文本输入 -->
          <template v-if="item.question_type == 'text'">
            <u-input v-model="form.answer[index].answer_text" />
          </template>
        </up-form-item>
      </up-form>
    </view>
    <view class="footer">
      <up-button type="primary" @click="submit">提交</up-button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { surveysApi, submissionsApi } from '@/api/api';
// 使用ref定义一个响应式变量
const uForm = ref(null);

// 使用reactive定义一个响应式对象
const form = reactive({
  answer: []
});
const rules = ref({});
const state = reactive({
  questionInfo: [],
  uRules: {
    'userInfo.name': {
      type: 'string',
      required: true,
      message: '请输入姓名',
      trigger: ['change', 'blur']
    }
  }
});

// 使用onMounted生命周期钩子
onLoad(() => {
  getQuestionList();
});

const getQuestionList = async () => {
  const res = await surveysApi();
  if (res.code === 200) {
    state.questionInfo = res.data;
    state.questionInfo.questions.map((item, index) => {
      form.answer[index] = {
        option_ids: [],
        answer_text: '',
        question_id: item.id
      };
      if (item.required) {
        const ruleKey =
          item.question_type === 'text'
            ? `form.answer.${index}.answer_text`
            : `form.answer.${index}.option_ids`;

        rules.value[ruleKey] = [
          {
            type: Array,
            required: true,
            message: item.question_type === 'text' ? '请填写此项' : '请选择一项',
            trigger: ['change', 'blur']
          }
        ];
      }
    });
    console.log(rules);
  } else {
    console.error('接口调用失败:', res);
  }
};

const submit = async () => {
  console.log(form.answer);
  form.answer.map((item) => {
    item.option_ids = item.option_ids.join(',');
  });
  const data = {
    answers: form.answer,
    phone_number: uni.getStorageSync('userInfo').mobile,
    survey_num: 'S001'
  };
  const result = await submissionsApi(data);
  if (result.code === 200) {
    uni.$u.toast('提交成功');
    uni.switchTab({
      url: '/pages/index/index'
    });
  }
  // uni.request({
  //   url: 'http://47.117.179.55:8080/api/submissions', // 替换为实际的接口URL
  //   method: 'post',
  //   data,
  //   success: (res) => {
  //     if (res.data.code === 200) {
  //       uni.$u.toast('提交成功');
  //       uni.switchTab({
  //         url: '/pages/index/index'
  //       });
  //     } else {
  //       uni.$u.toast(res.data.msg);
  //       // console.error('接口调用失败:', res);
  //     }
  //   },
  //   fail: (err) => {
  //     console.error('接口调用错误:', err);
  //   }
  // });
  // uForm.value.validate((valid) => {
  //   if (valid) {

  //   } else {
  //     // 校验未通过
  //     console.log('校验未通过');
  //   }
  // });
};
</script>
<style lang="scss" scoped>
/* 在这里添加样式代码 */
.custom-rate {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(90deg, #ffffff 0%, #7da02f 100%);
  border: solid 1px #f0f0f0;
  height: 40px;
  margin-top: 20rpx;

  .item {
    background: white;
    text-align: center;
    width: 25%;
    height: 40px;
    line-height: 40px;

    &.active {
      background: transparent;
    }
  }
}
</style>
